import { multiply, divide } from '../services/calculator.js'
import key from 'keymaster';

export default {
    namespace: 'calculator',
    state: {result: 0, memo: 0},
    reducers: {
      'add'(state, { payload: obj }) {
        const {num1, num2} = obj
        return { ...state, result: num1 + num2 }
      },
      subtract(state, { payload: obj  }) {
        const {num1, num2} = obj
        return { ...state, result: num1 - num2 }
      },
      save(state, { payload: num }) {
        return { ...state, result: num }
      },
      memo(state) {
        return { ...state, memo: state.result }
      },
    },
    effects: {
        *multiply({ payload: obj  }, { call, put }) {  // eslint-disable-line
            const {num1, num2} = obj
            const data = yield call(multiply, num1, num2);
            yield put({ type: 'save', payload: data });
        },
        *divide({ payload: obj  }, { call, put }) {  // eslint-disable-line
            const {num1, num2} = obj
            const data = yield call(divide, num1, num2);
            yield put({ type: 'save', payload: data });
        },
    },
    subscriptions: {
      setupHistory({ dispatch, history }){
        history.listen((location) => {
          dispatch ({type: "memo"})  
          console.log(location)   //这里可以获取当前变化的history路径以及参数，hash所有值，这样就可以在路由地址变化后做处理
        })
      },
      keyEvent({ dispatch }) {
        key('ctrl+0, ctrl+up', () => {
          console.log("keyEvent")
          dispatch({type:'memo'})
        });
      }
    }
  };